#include "thingNetwork.h"

ThingNetwork::ThingNetwork()
{
    port=10000; //thing处理默认端口
    socket=new QTcpSocket();
}

QJsonObject ThingNetwork::sendThings(QString username, QString password, QJsonArray things)
{
    socket->connectToHost(ip,port); //连接到服务器
    QJsonObject object;
    object.insert("id",username);   //添加id
    object.insert("password",password); //添加密码
    object.insert("things",things); //添加数据
    QJsonObject envelope;
    envelope.insert("code",2);  //设置请求代号为2
    envelope.insert("object",object);   //设置对象

    //将envelope转换为string
    QJsonDocument document;
    document.setObject(envelope);
    QByteArray byteArray = document.toJson(QJsonDocument::Compact);
    QString strEnvelope(byteArray);

    //qDebug()<<strEnvelope;
    char sendMsgChar[strEnvelope.length()+10]={0};
    strcpy(sendMsgChar,strEnvelope.toStdString().c_str());
    strcat(sendMsgChar,"\r\n");               //这里真是*了狗了，不加换行不算结束,无法得到哦回复emmm
    socket->write(sendMsgChar,strlen(sendMsgChar));  //发送信息
    QString res="";
    if(socket->waitForReadyRead(3000))  //从服务器端读到回复
    {
        res=QString(socket->readAll());
    }
    socket->disconnect();    //关闭连接
    //qDebug()<<res;
    //将回复转换为json对象
    QJsonParseError json_error;
    document=QJsonDocument::fromJson(res.toStdString().c_str(),&json_error);    //获取文档
    if(json_error.error!=QJsonParseError::NoError){qDebug()<<"出错";}//如果出错
    envelope=document.object(); //获取回复的信封
    return envelope;    //返回信封
}

QJsonObject ThingNetwork::getThings(QString username, QString password)
{
    //准备信封
    QJsonObject object;
    object.insert("id",username);   //添加id
    object.insert("password",password); //添加密码
    QJsonObject envelope;
    envelope.insert("code",1);  //请求代号为1，获取接口
    envelope.insert("object",object);   //设置对象
    //发送请求并返回信封
    return sendReq(envelope);
}

QJsonObject ThingNetwork::deleteThings(QString username, QString password, QJsonArray thingIds)
{
    //准备信封
    QJsonObject object;
    object.insert("id",username);   //添加id
    object.insert("password",password); //添加密码
    object.insert("thingsId",thingIds);  //设置id列表
    QJsonObject envelope;
    envelope.insert("code",3);  //请求代号为3,删除接口
    envelope.insert("object",object);   //设置对象
    //发送请求并返回信封
    return sendReq(envelope);
}
